<template>
  <div class="login-content">
    <el-card shadow="never" class="login-border">
      <h1 class="margin-b15">登录</h1>
      <el-form ref="form" :model="info" :rules="rules" label-width="60px">
        <el-form-item label="账号：" prop="username">
          <el-input v-model="info.username" />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input type="password" v-model="info.password"/>
        </el-form-item>
      </el-form>
      <div class="margin-b15" style="text-align: left">
        <el-switch v-model="rememberPwd" class="margin-r5"/>
        <span>记住密码</span>
      </div>
      <el-button :loading="loading" type="primary" size="small" class="login-btn" @click="loginClick">登录</el-button>
      <div class="margin-t15">power by xxx</div>
    </el-card>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
const { mapGetters, mapMutations } = createNamespacedHelpers('app')
export default {
  data() {
    return {
      isLogin: false,
      loading: false,
      rememberPwd: false,
      info: {},
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['loginInfo'])
  },
  mounted() {
    this.info = {
      username: this.loginInfo.username,
      password: this.loginInfo.password
    }
    this.rememberPwd = this.loginInfo.rememberPwd
  },
  methods: {
    ...mapMutations(['setLoginInfo', 'setUserInfo']),
    loginClick() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          setTimeout(() => {
            this.loading = false
            // test login
            this.setUserInfo({
              ...this.info,
              uid: 1
            })
            this.rememberLoginInfo()
            this.$router.replace('/')
          }, 500)
        }
      })
    },
    rememberLoginInfo() {
      const data = {
        username: this.info.username,
        rememberPwd: this.rememberPwd
      }
      if (this.rememberPwd) {
        data.password = this.info.password
      }
      this.setLoginInfo(data)
    }
  }
}
</script>

<style lang="scss" scoped>
  .login-content {
    background-color: lightskyblue;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    h1 {
      font-size: 20px;
      text-align: center;
    }
    .login-border {
      width: 320px;
      height: 260px;
      padding: 10px 15px;
      box-shadow: 0 2px 15px 0 rgba(90,123,239,.36);
      .login-btn {
        width: 100%;
      }
    }
  }

</style>
